﻿#include "mainwindow.h"
#include "qmessagebox"
#include "iostream"
#include <QMediaPlayer>
#include "torchhelper.h"
using namespace cv;
using namespace std;
mainwindow::mainwindow(QWidget *parent)
    : QMainWindow(parent)
{
    std::cout << "cuda::is_available():" << torch::cuda::is_available()<<"\n";
    ui.setupUi(this);    
    init_Form();
    initPlayer();
    imgshow = make_shared<imageshow>();
    init_torch("yolov8s.torchscript");
}



void mainwindow::init_torch(const string& modelpath)
{
    at::init_num_threads();
    at::set_num_threads(16);
    try
    {
        torch_module = torch::jit::load(modelpath);
        torch_module.eval();
        torch_module.to(device, torch::kFloat32);
    }
    catch (c10::Error& e)
    {
        cout << e.msg() << "\n";
    }
}
void mainwindow::nextFrame()
{
   
    
    if (capture.isOpened())
    {
        capture.read(frame);
        if (frame.empty())
        {
            return;
        }
        cv::resize(frame, rezie, { m_videolabelSize.width(),  m_videolabelSize.height() });
        cvtColor(rezie, rgb, COLOR_BGR2RGB);
        /*for (size_t i = 0; i < 1080; i++)
        {
            for (size_t j = 0; j < 1920; j++)
            {

                bufferimg->setPixel(j,i, qRgb(rgb.data[(i*1920+j)*3], rgb.data[(i * 1920 + j)*3+1], rgb.data[(i * 1920 + j) * 3  +2]) );
            }
        }*/
        
            run(rgb, torch_module, classes, device);
            if (ready2take)
            {
                ready2take = false;
	            const auto filename = sysInfo->text();
                auto partname =  filename.split(':');
                auto tempname = QString("");
                
                if (filename.isEmpty())
                {
                    return;
                }
                for (const auto char_ : partname)
                {
                    tempname += char_;
                }
                auto stdname = filename.toStdString();

                ui.listWidget->addItem(new QListWidgetItem(tempname));
                imwrite(tempname.toStdString() +".jpg", rgb);
                cout << tempname.toStdString();
            }
       
     
        //memcpy_s(bufferimg->bits(), m_videolabelSize.height() * m_videolabelSize.width() * 3, rgb.data, m_videolabelSize.width() * m_videolabelSize.height() * 3);
        //const QImage tempimg((uchar*)rgb.data,rgb.cols,rgb.rows,static_cast<long long>(rgb.step1()),QImage::Format_RGB888);
        ui.label->setPixmap(QPixmap::fromImage(*bufferimg));
        //ui.label->setPixmap(QPixmap::fromImage(tempimg));
    }
}

void mainwindow::on_btnSnap_clicked()
{   
    capture.set(CAP_PROP_POS_FRAMES, 0);
}

void mainwindow::initPlayer()
{
    ui.cmb_CameraName->addItem("CAM1");
    framerate = 0;
    channels = 0;
    capture.open("test.mp4");  
    capture >> frame;
    framerate = static_cast<int>(capture.get(VideoCaptureProperties::CAP_PROP_FPS));
    const auto labelSize = ui.label->size();   
    channels = frame.channels();
    capture.set(CAP_PROP_POS_FRAMES, 0);
    m_videolabelSize = QSize( labelSize.width(), labelSize.height());
    cv::resize(frame, rezie, { m_videolabelSize.width(), m_videolabelSize.height() });
    cvtColor(rezie, rgb, COLOR_BGR2RGB);
    bufferimg = make_shared<QImage>(rgb.data, rezie.cols, rezie.rows, QImage::Format_RGB888); // 无效是因为rgb没有初始化
    frametimer = make_shared<QTimer>(this);
    connect(frametimer.get(), &QTimer::timeout, this, &mainwindow::nextFrame);
    frametimer->start(1000 / framerate);
    snaptimer = make_shared<QTimer>(this);
    snaptimer->start(2000);
    connect(snaptimer.get(), &QTimer::timeout, this, &mainwindow::ready2takeshot);
}



void mainwindow::init_Form()
{

    sysInfo = make_shared<QLabel>(this);
    Sys_timer = make_shared<QTimer>(this);
    Sys_timer->start(1000);
    connect(Sys_timer.get(), &QTimer::timeout, this, &mainwindow::setTimerLabel);
    statusBar()->setSizeGripEnabled(false);
    statusBar()->setStyleSheet(QString("QStatusBar::item{border: 2px}"));
    statusBar()->setSizeGripEnabled(false);
    ui.statusBar->addPermanentWidget(sysInfo.get());
}



void mainwindow::on_btnVideo_clicked() const
{
    QMessageBox::information(nullptr, "info", QString("帧率:%1,通道:%2").arg(framerate).arg(channels), QMessageBox::Ok);
}

void mainwindow::ready2takeshot()
{
    ready2take = true;
}

void mainwindow::on_btnInspect_clicked() const
{
	if (auto selected = ui.listWidget->currentItem())
    {
        auto img = imread(selected->text().toStdString()+".jpg");
        
        //auto showimg = QImage(img.data, rezie.cols, rezie.rows, QImage::Format_RGB888);
        imgshow->show();
        imgshow->setimg(img);
      //  form.ui.label->setPixmap(QPixmap::fromImage(showimg));
    }
}

void mainwindow::setTimerLabel() const
{
	const QDateTime Date_Time = QDateTime::currentDateTime();
	const QString Time_system = Date_Time.toString("yyyy-MM-dd hh:mm:ss ddd");
    sysInfo->setText(Time_system);
}


